<?php
namespace app\common\service;

use app\common\helper\UserCardHelper;
use app\common\util\Upload;
use think\Model;
use app\common\model\User;
use app\common\model\UserIntegral;
use think\Request;
use app\common\model\Students;
use app\common\model\Visiting;
use app\common\model\TagUser;
use app\common\model\Track;
use app\common\helper\WeixinHelper;
use app\common\util\Util;

class UserService extends BaseService
{

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 获取会员（顾问）信息
     * @param User $userModel
     * @param int $sid
     * @param int $uid
     */
    public function getUserInfo(UserIntegral $uiModel, $sid, $uid)
    {
        $user_integral = $this->getCounselorInfo($uiModel, $sid, $uid);
        if (!$user_integral) {
            return false;
        }

        if ($user_integral->user->status == 0) {
            return false;
        }

        $user = $user_integral->user->toArray();
        $user_info = array();
        $user_info['user_name'] = $user['user_name'];
        $user_info['user_mobile'] = $user['user_mobile'];
        $user_info['user_qrcode'] = $user['user_qrcode'];
        $user_info['user_nickname'] = $user['user_nickname'];
        $user_info['user_headimgurl'] = $user['user_headimgurl'];
        //获取会员等级
        if (!$user_integral->counselor_rank_id) {
            $user_info['rank_name'] = '';
        } else {
            $rank = db('counselor_rank')->where(['counselor_rank_id' => $user_integral->counselor_rank_id])->find();
            if (empty($rank)) {
                $user_info['rank_name'] = '';
            } else {
                if ($rank['status'] == 0) {
                    $user_info['rank_name'] = '';
                } else {
                    $user_info['rank_name'] = $rank['name'];
                }
            }
        }
        //推广二维码
        $userCardHelper = new UserCardHelper();
        $user_card = $userCardHelper->get_user_card_only($sid, $uid);
        $user_info['user_card'] = $user_card;

        return $user_info;
    }


    /**
     * 获得用户的全部信息
     * @param $sid
     * @param $uid
     * @return array|bool
     */
    public function getUserAllInfo($sid, $uid)
    {

        $where = [
            'sid' => $sid,
            'userid' => $uid,
        ];
        //'counselor_status' => 1
        $user_integral = UserIntegral::get($where);
        if (!$user_integral) {
            return false;
        }

        if ($user_integral->user->status == 0) {
            return false;
        }

        $user = $user_integral->user->toArray();
        $user_info = array();
        $user_info['user_name'] = $user['user_name'];
        $user_info['user_mobile'] = $user['user_mobile'];
        $user_info['user_qrcode'] = $user['user_qrcode'];
        $user_info['user_nickname'] = $user['user_nickname'];
        $user_info['user_headimgurl'] = $user['user_headimgurl'];

        //获取会员等级
        if (!$user_integral->rankid) {
            $user_info['rank_level'] = 0;
            $user_info['rank_name'] = '';
        } else {
            $rank = $user_integral->rank; //rank对象

            if (empty($rank)) {
                $user_info['rank_level'] = 0;
                $user_info['rank_name'] = '';
            } else {
                $rank = $rank->data;
                if ($rank['status'] == 0) {
                    $user_info['rank_level'] = 0;
                    $user_info['rank_name'] = '';
                } else {
                    $user_info['rank_level'] = $rank['level'];
                    $user_info['rank_name'] = $rank['name'];
                }
            }
        }

        //推广二维码
        $userCardHelper = new UserCardHelper();
        $user_card = $userCardHelper->get_user_card_only($sid, $uid);
        $user_info['user_card'] = $user_card;

        return $user_info;
    }


    public function editUserInfo(UserIntegral $uiModel, Request $request)
    {
        $sid = $request->param('sid');
        $uid = $request->param('uid');

        $user_integral = $this->getCounselorInfo($uiModel, $sid, $uid);

        if (!$user_integral) {
            return ['status' => 0, 'msg' => '不存在此用户'];
        }

        $user = $user_integral->user;

        //上传个人二维码
        if ($request->file('file')) {
            $file = $request->file('file'); //个人二维码
            if (empty($file)) {
                return ['status' => 0, 'msg' => '请选择上传图片'];
            }
//            $path = '../../../Uploads/User/qrcode/'.date('Y-m-d').'/';
//            $info = $file->validate(['size'=>2 * 1024 * 1024,'ext'=>'jpg,png,gif,jpeg'])->rule('uniqid')->move($path);
            $info = Upload::uploadFile();

            if ($info) {
//                $user_qrcode = '/Uploads/User/qrcode/'.date('Y-m-d').'/'.$info->getFilename();
                $user_qrcode = Util::qiniu_url($info);

                $data = [
                    'status' => 1,
                    'data' => [
                        'img_path' => $user_qrcode
//                        'domain' => 'http://'.$request->server('SERVER_NAME')
                    ],
                    'msg' => '上传成功'
                ];

                $user->user_qrcode = $user_qrcode;

                $res = $user->save();

                if ($res === false) {
                    return ['status' => 0, 'msg' => '修改失败', 'data' => ''];
                } else {
                    return $data;
                }
            } else {
                return ['status' => 0, 'msg' => '上传失败', 'data' => ''];
            }
        }

        //保存students表更新数据
        $student_update_data = [];

        if ($request->has('user_name')) {
            $user->user_name = $request->param('user_name');
            $student_update_data['name'] = $request->param('user_name');
        }

        if ($request->has('user_mobile')) {
            $user->user_mobile = $request->param('user_mobile');
            $student_update_data['phone'] = $request->param('user_mobile');
        }

        $res = $user->save();

        //更新student表中相应字段
        db('students')->where(['sid' => $sid, 'uid' => $uid])->update($student_update_data);

        if ($res === false) {
            return ['status' => 0, 'msg' => '修改失败', 'data' => ''];
        } else {
            return ['status' => 1, 'msg' => '修改成功', 'data' => ''];
        }

    }


    /**
     * 获取客户详情
     * @param UserIntegral $uiModel
     * @param int $sid
     * @param int $uid
     * @param int $cid
     * @return boolean|unknown[]|mixed[]|NULL[]
     */
    public function getCustomerInfo(UserIntegral $uiModel, $sid, $uid, $cid)
    {
        $where = [
            'userid' => $cid,
            'sid' => $sid,
            'parent_id|counselor_id' => $uid,
            'counselor_status' => 0,
            'students_id' => ['>', 0]
        ];
        $customer = $uiModel::get($where);

        //判断会员状态和是否存在客户Id
        if (empty($customer) || $customer->user->status == 0) {
            return false;
        }

        //保存客户基本信息
        $user = $customer->user->data;

        //获取客户资料
//        $student = db('students')->where(['id' => $customer->students_id])->find();
        $student = db('students')->where(['uid' => $cid, 'sid' => $sid])->find();
        if (empty($student) || $student['status'] == 0) {
            return false;
        }

        $customer_info = array();
        $customer_info['cid'] = $customer['userid'];
        $customer_info['user_nickname'] = $user['user_nickname'];
        $customer_info['user_headimgurl'] = $user['user_headimgurl'];
        $customer_info['is_subscribe'] = $customer->is_subscribe; //是否关注
        $customer_info['phone'] = $student['phone'];

        $customer_info['real_name'] = $student['name'];

        //获取客户公司名称及地址  这里读取所有的公司信息
        if (!empty($student['company'])) {
//            $customer_info['company'] = unserialize($student['company']);
//            $temp = preg_replace_callback('#s:(\d+):"(.*?)";#s',function($match){return 's:'.strlen($match[2]).':"'.$match[2].'";';}, $student['company']);
//            $customer_info['company'] = unserialize($temp);
            $customer_info['company'] = Util::unserializeStr($student['company']);
        } else {
            $customer_info['company'][0]['cname'] = '';
            $customer_info['company'][0]['position'] = '';
            $customer_info['company'][0]['address'] = '';
            $customer_info['company'][0]['lat'] = ''; //地址纬度
            $customer_info['company'][0]['lng'] = ''; //地址经度
        }

        $customer_info['website'] = $student['website']; //网站
        $customer_info['remark'] = $student['remark'];  //备注

        //标签
        $tagService = new TagService();
        $tuModel = new TagUser();
        $customer_info['tags'] = $tagService->getUserTagList($sid, $cid, 1);
        //下次拜访时间
        $customer_info['next_time'] = $this->getVisitingNextTime($sid, $uid, $cid);

        return $customer_info;
    }

    public function getCustomerInfoNew(UserIntegral $uiModel, $sid, $uid, $student_id)
    {
        $field = 's.id as student_id,s.uid as cid,s.phone,s.name as real_name,s.company,s.website,s.remark,u.user_nickname,
        u.user_headimgurl,ui.is_subscribe';
        $where = [
            's.sid' => $sid,
            's.id' => $student_id,
            'ui.parent_id|ui.counselor_id|s.counselor_id' => $uid,
            's.is_counselor' => 0
        ];
        $customer_info = db('students s')
            ->field($field)
            ->join('user u', 's.uid=u.user_id', 'LEFT')
            ->join('user_integral ui', 'ui.userid=s.uid', 'LEFT')
            ->where($where)
            ->find();

        //获取客户公司名称及地址  这里读取所有的公司信息
        if (!empty($customer_info['company'])) {
            $customer_info['company'] = Util::unserializeStr($customer_info['company']);
        } else {
            $customer_info['company'][0]['cname'] = '';
            $customer_info['company'][0]['position'] = '';
            $customer_info['company'][0]['address'] = '';
            $customer_info['company'][0]['lat'] = ''; //地址纬度
            $customer_info['company'][0]['lng'] = ''; //地址经度
        }


        //标签
        $tagService = new TagService();
        $tuModel = new TagUser();
        $customer_info['tags'] = $tagService->getUserTagListNew($sid, $customer_info['cid'], $student_id, 1);
        //下次拜访时间
        $customer_info['next_time'] = $this->getVisitingNextTimeNew($sid, $uid, $customer_info['cid'], $student_id);

        return $customer_info;
    }


    /**
     * 获取客户列表
     * @param UserIntegral $uiModel
     * @param int $sid
     * @param int $uid
     * @param int $p 分页参数
     */
    public function getCustomerList(UserIntegral $uiModel, Request $request, $p)
    {

        $tagService = new TagService();
        $trackService = new TrackService();
        $tuModel = new TagUser();
        $trackModel = new Track();

        $sid = $request->param('sid');
        $uid = $request->param('uid');

        //客户类型 （正式客户:1）（意向客户:2）
        if ($request->has('type') && !empty($request->param('type'))) {
            $type = $request->param('type');
        } else {
            $type = 1;
        }

        /*
        $where = [
            'ui.counselor_status' => [[null],['neq', 1],'or'],
            's.sid' => $sid,
            'ui.parent_id|ui.counselor_id|s.counselor_id' => $uid,
            's.formal_status' => $type == 1 ? 1 : 0
        ];
        */

//        $where = '(`ui`.`counselor_status` IS NULL or `ui`.`counselor_status` != 1)  AND
//        `s`.`sid` =' . $sid . '   AND
//         ( `ui`.`parent_id` = ' . $uid . ' OR `ui`.`counselor_id` = ' . $uid . ' OR `s`.`counselor_id` = ' . $uid . ' )  AND
//         `s`.`formal_status` = ' . ($type == 1 ? 1 : 0);
        $where = [
            's.is_counselor' => 0,
            's.sid' => $sid,
            'ui.parent_id|ui.counselor_id|s.counselor_id' => $uid,
            's.formal_status' => $type == 1 ? 1 : 0
        ];


        //查询字段
        $field = 's.uid as cid,u.user_nickname,u.user_headimgurl,ui.is_subscribe,s.id as student_id,s.name as real_name,
        s.company,s.phone,s.track_update_time,s.visiting_update_time';
//        $group = 's.uid,u.user_nickname,u.user_headimgurl,ui.is_subscribe,s.id,s.name,s.company,s.phone';

        $customer_list = array();  //保存客户列表

        //按标签搜索
        if ($request->has('search_tag') && !empty($request->param('search_tag'))) {
            //tag_id的数组
            $search_tag = $request->param('search_tag');
            $tag_ids = explode(',', $search_tag);

            $group = 's.id,s.uid,s.name,s.company,s.phone,ui.is_subscribe,u.user_nickname,u.user_headimgurl';

            //子查询
            /*$subQuery = db('tag_user')->where(['store_id' => $sid, 'tag_id' => ['in', $search_tag]])->buildSql();
            $customer_list = db()->table($subQuery . ' tu')
                ->field($field)
                ->join('students s', 's.uid = tu.uid', 'LEFT')
                ->join('user_integral ui', 'ui.userid = s.uid', 'LEFT')
                ->join('user u', 'tu.uid = u.user_id', 'LEFT')
                ->join('visiting v', 'tu.uid = v.uid', 'LEFT')
                ->join('track t', 's.sid = t.uid', 'LEFT')
                ->where($where)
                ->order("v.next_time DESC,t.pubdate DESC")
                ->group($group)
                ->having('count(*) >= ' . count($tag_ids))
                ->limit(($p - 1) * $this->pageSize, $this->pageSize)
                ->select();*/

            $where['tu.tag_id'] = ['in', $tag_ids];

            $customer_list = db('students s')
                ->field($field)
                ->join('tag_user tu', 's.id=tu.student_id', 'LEFT')
                ->join('user_integral ui', 'ui.userid = s.uid', 'LEFT')
                ->join('user u', 's.uid = u.user_id', 'LEFT')
                ->where($where)
                ->order('s.visiting_update_time DESC,s.track_update_time DESC')
                ->group($group)
                ->limit(($p - 1) * $this->pageSize, $this->pageSize)
                ->select();

            /*if ($type == 1){
                $order = "v.next_time DESC";
                $customer_list =db()->name('students')
                            ->alias('s')->join('user_integral ui','ui.userid = s.uid and ui.sid = s.sid','LEFT')
                            ->field($field)
                            ->join('tag_user tu','s.uid = tu.uid','LEFT')
                            ->join('user u','s.uid = u.user_id','LEFT')
                            ->join('visiting v','s.uid = v.uid AND ui.sid = v.store_id','LEFT')
                            ->where($where)
                            ->where('tu.tag_name', ['in', $request->param('search_tag')])
//                            ->whereLike('tu.tag_name', $request->param('search_tag'))
                            ->order($order)
//                            ->group($group)
                            ->limit(($p-1) * $this->pageSize , $this->pageSize)
                            ->select();
            } elseif ($type == 2){
                $order = "t.pubdate DESC";
//                 $where['t.pid'] = $request->param('uid');
                $customer_list = db()->name('students')
                            ->alias('s')->join('user_integral ui','ui.userid = s.uid and ui.sid = s.sid','LEFT')
                            ->field($field)
                            ->join('tag_user tu','s.uid = tu.uid','LEFT')
                            ->join('user u','s.uid = u.user_id','LEFT')
                            ->join('track t','s.uid = t.uid AND ui.sid = t.sid','LEFT')
                            ->where($where)
                            ->where('tu.tag_name', ['in', $request->param('search_tag')])
//                            ->whereLike('tu.tag_name', $request->param('search_tag'))
                            ->order($order)
//                            ->group($group)
                            ->limit(($p-1) * $this->pageSize , $this->pageSize)
                            ->select();
            }*/
        } else {
            //常规搜索
            //按客户名称搜索
            if ($request->has('search_name') && !empty($request->param('search_name'))) {
                $where['s.name'] = ['like', '%' . $request->param('search_name') . '%'];
            }

            /*$customer_list = db()->name('students')
                ->alias('s')
                ->field($field)
                ->join('user_integral ui', 'ui.userid = s.uid and ui.sid = s.sid', 'LEFT')
                ->join('user u', 's.uid = u.user_id', 'LEFT')
                ->join('visiting v', 's.uid = v.uid AND ui.sid = v.store_id', 'LEFT')
                ->join('track t', 's.sid = t.uid AND ui.sid = t.sid', 'LEFT')
                ->where($where)
                ->order("v.next_time DESC,t.pubdate DESC")
                ->limit(($p - 1) * $this->pageSize, $this->pageSize)
                ->select();*/
            $customer_list = db('students s')
                            ->field($field)
                            ->join('user_integral ui', 'ui.userid = s.uid and ui.sid = s.sid', 'LEFT')
                            ->join('user u', 's.uid = u.user_id', 'LEFT')
                            ->where($where)
                            ->order('s.visiting_update_time DESC,s.track_update_time DESC')
                            ->limit(($p - 1) * $this->pageSize, $this->pageSize)
                            ->select();

            /*if ($type == 1){
                $order = "v.next_time DESC";
                $customer_list = db()->name('students')
                                ->alias('s')
                                ->field($field)
                                ->join('user_integral ui','ui.userid = s.uid and ui.sid = s.sid','LEFT')
                                ->join('user u','s.uid = u.user_id','LEFT')
                                ->join('visiting v','s.uid = v.uid AND ui.sid = v.store_id','LEFT')
                                ->where($where)
                                ->order($order)
//                                ->group($group)
                                ->limit(($p-1) * $this->pageSize , $this->pageSize)
                                ->select();
            } elseif ($type == 2){
                $order = "t.pubdate DESC";
//                 $where['t.pid'] = $request->param('uid');
                $customer_list = db()->name('students')
                                ->alias('s')
                                ->field($field)
                                ->join('user_integral ui','ui.userid = s.uid and ui.sid = s.sid','LEFT')
                                ->join('user u','s.sid = u.user_id','LEFT')
                                ->join('track t','s.sid = t.uid AND ui.sid = t.sid','LEFT')
                                ->where($where)
                                ->order($order)
//                                ->group($group)
                                ->limit(($p-1) * $this->pageSize , $this->pageSize)
                                ->select();
            }*/
        }

        if ($customer_list) {
            foreach ($customer_list as $k => $v) {
                if (!empty($v['company'])) {
//                    $company = unserialize($v['company']);
//                    $temp = preg_replace_callback('#s:(\d+):"(.*?)";#s',function($match){return 's:'.strlen($match[2]).':"'.$match[2].'";';}, $v['company']);
//                    $company = unserialize($temp);
                    $company = Util::unserializeStr($v['company']);

                    $customer_list[$k]['company'] = $company;
                    $customer_list[$k]['cname'] = $company[0]['cname'];
                } else {
                    $customer_list[$k]['cname'] = '';
                }

                //最新动态
                $recent_news = $trackService->getOneRecentTrackByCID($request->param('sid'), $request->param('uid'), $v['cid']);
                $recent_news_msg = $recent_news ? '阅读了:' . $recent_news['msg'] : '';
                $customer_list[$k]['recent_news'] = $recent_news_msg;

                //标签
//                $customer_list[$k]['tags'] = $tagService->getUserTagList($request->param('sid'), $v['cid'], 1);
                $customer_list[$k]['tags'] = $tagService->getUserTagListNew2($request->param('sid'), $v['cid'], $v['student_id'], 1);

                //下次拜访时间
                $customer_list[$k]['next_time'] = $this->getVisitingNextTime($request->param('sid'), $request->param('uid'), $v['cid']);
            }
        }

        return $customer_list;
    }

    /**
     * 修改客户资料
     * @param UserIntegral $uiModel
     * @param Request $request
     * @return number[]|string[]
     */
    public function editCustomer(UserIntegral $uiModel, Request $request)
    {
        $where = [
            'ui.sid' => $request->param('sid'),
            'ui.parent_id' => $request->param('uid'),
            'ui.userid' => $request->param('cid'),
            'ui.counselor_status' => 0,
            'ui.students_id' => ['>', 0]
        ];

        //$customer = $uiModel::get($where);

        //获取客户资料对象
        //$student = $customer->students;

        $student = db('user_integral')
            ->alias('ui')
            ->join('students s', 's.uid = ui.userid and s.sid = ui.sid')
            ->where($where)
            ->find();

        if (empty($student)) {
            return ['status' => 0, 'msg' => '未找到该用户'];
        }

        $postParam = $request->post();

        $save_data = array();
        $save_data['name'] = $postParam['real_name'];
        $save_data['phone'] = $postParam['phone'];
        $save_data['phone_bind_status'] = 1; //默认绑定

        if ($request->has('website') && !empty($postParam['website'])) {
            $save_data['website'] = $postParam['website'];
        }

        if ($request->has('remark') && !empty($postParam['remark'])) {
            $save_data['remark'] = $postParam['remark'];
        }

        if ($request->has('company') && !empty($postParam['company'])) {
//            $save_data['company'] = serialize($postParam['company']);
            $save_data['company'] = Util::serializeStr($postParam['company']);
        }
        $res = db('students')->where(['sid' => $request->param('sid'), 'uid' => $request->param('cid')])->update($save_data);
        //更新user表中的手机号码
        db('user')->where(['user_id' => $request->param('cid')])->update(['user_mobile' => $save_data['phone']]);

        if (false === $res) {
            return ['status' => 0, 'msg' => '修改失败'];
        } else {
            return ['status' => 1, 'msg' => '修改成功'];
        }
    }

    public function editCustomerNew(UserIntegral $uiModel, Request $request)
    {
        $where = [
            's.id' => $request->param('student_id'),
            's.sid' => $request->param('sid'),
            'ui.parent_id|ui.counselor_id|s.counselor_id' => $request->param('uid'),
            's.is_counselor' => 0
        ];

        $student = db('students s')
            ->join('user_integral ui', 's.uid=ui.userid', 'LEFT')
            ->where($where)
            ->find();

        if (empty($student)) {
            return ['status' => 0, 'msg' => '未找到该用户'];
        }

        $postParam = $request->post();

        $save_data = array();
        $save_data['name'] = $postParam['real_name'];
        $save_data['phone'] = $postParam['phone'];
        $save_data['phone_bind_status'] = 1; //默认绑定

        if ($request->has('website') && !empty($postParam['website'])) {
            $save_data['website'] = $postParam['website'];
        }

        if ($request->has('remark') && !empty($postParam['remark'])) {
            $save_data['remark'] = $postParam['remark'];
        }

        if ($request->has('company') && !empty($postParam['company'])) {
//            $save_data['company'] = serialize($postParam['company']);
            $save_data['company'] = Util::serializeStr($postParam['company']);
        }
        $res = db('students')
            ->where([
                'sid' => $request->param('sid'),
                'id' => $request->param('student_id')
            ])
            ->update($save_data);

        //更新user表中的手机号码
        if ($student['uid'] > 0) {
            db('user')->where(['user_id' => $student['uid']])->update(['user_mobile' => $save_data['phone']]);
        }

        if (false === $res) {
            return ['status' => 0, 'msg' => '修改失败'];
        } else {
            return ['status' => 1, 'msg' => '修改成功'];
        }
    }

    /**
     * 获取粉丝列表
     * @param UserIntegral $uiModel
     * @param Request $request
     * @param unknown $p
     * @return number
     */
    public function getFansList(UserIntegral $uiModel, Request $request, $p)
    {
        //获取排序类型
        if ($request->has('type') && !empty($request->param('type'))) {
            $type = $request->param('type');
        } else {
            $type = 1;
        }

        $where = [
            'ui.sid' => $request->param('sid'),
            'ui.counselor_id' => $request->param('uid'),
            'ui.counselor_status' => 0,
            'ui.students_id' => 0,
        ];

        //按粉丝昵称搜索
        if ($request->has('search_name') && !empty($request->param('search_name'))) {
            $where['u.user_nickname'] = ['like', '%' . $request->param('search_name') . '%'];
        }

        $field = 'u.user_id as fid,u.user_nickname,u.user_headimgurl,ui.is_subscribe,ui.addtime,ui.is_read,ui.sid,ui.counselor_id';

        $group = 'ui.userid';

        $fans = array();

        if ($type == 1) {
            //按“最新”排序
            $order = 'ui.addtime DESC';
            $fans = db()->name('user_integral')
                ->alias('ui')
                ->field($field)
                ->join('user u', 'ui.userid = u.user_id')
                ->where($where)
                ->order($order)
                ->limit(($p - 1) * $this->pageSize, $this->pageSize)
                ->select();
        } elseif ($type == 2) {
            //按“活跃度”排序
            $order = 't_count DESC';
            $field = $field . ',COUNT(t.uid) as t_count';
            $group .= ',ui.is_subscribe,ui.addtime,ui.is_read,ui.sid';
            $fans = db()->name('user_integral')
                ->alias('ui')
                ->field($field)
                ->join('user u', 'ui.userid = u.user_id')
                ->join('track t', 'ui.userid = t.uid AND ui.sid = t.sid', 'LEFT')
                ->where($where)
                ->order($order)
                ->group($group)
                ->limit(($p - 1) * $this->pageSize, $this->pageSize)
                ->select();
        } elseif ($type == 3) {
            //是否为“好友”
            $where['t.natural_id'] = $request->param('uid');
            $group .= ',ui.is_subscribe,ui.addtime,ui.is_read,ui.sid';
            $fans = db()->name('user_integral')
                ->alias('ui')
                ->field($field)
                ->join('user u', 'ui.userid = u.user_id')
                ->join('track t', 'ui.userid = t.uid AND ui.sid = t.sid', 'LEFT')
                ->where($where)
                ->group($group)
                ->limit(($p - 1) * $this->pageSize, $this->pageSize)
                ->select();
        }

        $fans_list = array();
        if ($fans) {
            foreach ($fans as $k => $v) {
                $fans_list[$k]['fid'] = $v['fid'];
                $fans_list[$k]['user_nickname'] = $v['user_nickname'];
                $fans_list[$k]['user_headimgurl'] = $v['user_headimgurl'];
                $fans_list[$k]['addtime'] = date('Y/m/d H:i', $v['addtime']);
                $fans_list[$k]['is_subscribe'] = $v['is_subscribe'];
                $fans_list[$k]['counselor_id'] = $v['counselor_id'];
                $fans_list[$k]['is_wxfriend'] = $this->isWxFriend($request->param('sid'), $v['fid'], $request->param('uid')); //是否为微信好友
                $fans_list[$k]['dynamic'] = $this->getFansDynamicCount($request->param('sid'), $v['fid'], $request->param('uid')); //动态总数
//                 $fans_list[$k]['interaction_times'] = 0; //互动次数

                //更改查看状态
                if ($v['is_read'] == 0) {
                    $this->changeIsReadStatus($v);
                }
            }
        }

        return $fans_list;
    }

    public function changeIsReadStatus($user)
    {
        UserIntegral::update(['is_read' => 1], ['userid' => $user['fid'], 'sid' => $user['sid']]);
    }

    /**
     * 获取粉丝详情
     * @param UserIntegral $uiModel
     * @param int $sid
     * @param int $uid
     * @param int $fid
     * @return boolean|unknown[]|mixed[]|NULL[]
     */
    public function getFansInfo(UserIntegral $uiModel, $sid, $uid, $fid)
    {
        $where = [
            'userid' => $fid,
            'sid' => $sid,
            'parent_id|counselor_id' => $uid,
            'counselor_status' => 0,
            'students_id' => 0
        ];
        $fans = $uiModel::get($where);

        //判断会员状态和是否存在客户Id
        if (empty($fans) || $fans->user->status == 0) {
            return false;
        }

        //保存客户基本信息
        $user = $fans->user->data;

        $fans_info = array();
        $fans_info['fid'] = $fans['userid'];
        $fans_info['user_nickname'] = $user['user_nickname'];
        $fans_info['user_headimgurl'] = $user['user_headimgurl'];

        $fans_info['is_wxfriend'] = $this->isWxFriend($sid, $fid, $uid); //是否为微信好友
//         $fans_info['interaction_times'] = 0; //互动次数
        $fans_info['dynamic'] = $this->getFansDynamicCount($sid, $fid, $uid); //动态总数

        $fans_info['addtime'] = date('Y/m/d H:i', $fans->addtime); //加入时间

        return $fans_info;
    }

    /**
     * 获取顾问旗下的粉丝数量
     * @param $sid
     * @param $uid
     * @return int|string
     */
    public function getFansCount($sid, $uid)
    {
        $where = [
            'sid' => $sid,
            'parent_id|counselor_id' => $uid,
            'counselor_status' => 0,
            'students_id' => 0,
        ];
        return db('user_integral')->where($where)->count();
    }


    /**
     * 完善粉丝资料
     * @param UserIntegral $uiModel
     * @param Request $request
     * @return number[]|string[]
     */
    public function editFans(UserIntegral $uiModel, Request $request)
    {
        $sid = $request->param('sid');
        $fid = $request->param('fid');
        $pid = $request->param('uid');
        $where = [
            'sid' => $sid,
            'parent_id|counselor_id' => $pid,
            'userid' => $fid,
            'counselor_status' => 0,
            'students_id' => 0
        ];

        $fans = $uiModel::get($where);


        if (empty($fans)) {
            return ['status' => 0, 'msg' => '未找到该用户'];
        }

        $postParam = $request->post();

        $save_data = array();

        $save_data['sid'] = $fans->sid;
        $save_data['uid'] = $fans->userid;
        $save_data['user_integral_id'] = $fans->id;

        $save_data['name'] = $postParam['real_name'];
        $save_data['phone'] = $postParam['phone'];
        $save_data['addtime'] = time();

        if ($request->has('website')) {
            $save_data['website'] = $postParam['website'];
        }

        if ($request->has('remark')) {
            $save_data['remark'] = $postParam['remark'];
        }

        if ($request->has('company') && !empty($postParam['company'])) {
//            $save_data['company'] = serialize($postParam['company']);
            $save_data['company'] = Util::serializeStr($postParam['company']);
        }

        if (!empty($fans->students)) {
            return ['status' => 0, 'msg' => '完善资料失败。'];
        }

        //通过手机号码查询是否和老学员(students)表中的手机号码一致，一致则同步数据
        $org_student = db('students')->where(['sid' => $sid, 'phone' => $postParam['phone']])->find();
        if ($org_student) {
            $save_data['uid'] = $fid;
            $save_data['phone_bind_status'] = 1;
            $res = db('students')->where(['sid' => $sid, 'phone' => $postParam['phone']])->update($save_data);
            // 插入班级学员信息
            // 查询出班级学员表里面是否有这个学员，理论上只要是学员表里面有数据，班级学员表里面必然有记录
            // 如果没有就是出错了，需要开启事务保证
            // 未绑定的意向学员绕过
            if ($res['formal_status']) {
                $class_students = db('class_students')->where(['studentsid' => $org_student['id'], 'sid' => $sid])->field(true)->find();
                if (!$class_students) {
                    \think\Log::record('work:error->完善资料失败,学员信息出错！学员ID:' . $org_student['id'] . ' 在班级学员表里面没有记录！');
                    return ['status' => 0, 'msg' => '完善资料失败,学员信息出错！'];
                }
            }
            // 增加一个字段，学员表ID
            // 2017-08-07 LJiao
            if ($org_student['classid']) {
                db('class_students')->where([
                    'sid' => $sid,
                    'studentsid' => $org_student['id']
                ])->update(['uid' => $fid]);
            }
            // 学员表里面有顾问，那么优先使用这个学员表里面的顾问ID
            $counselor_id_temp = $org_student['counselor_id'];
            if ($counselor_id_temp) {
                $user_integral_data['parent_id'] = $counselor_id_temp;
                $user_integral_data['counselor_id'] = $counselor_id_temp;

                $user_integral_id = db('user_integral')->where(['sid' => $sid, 'userid' => $fid])->value('id');
                if ($user_integral_id) {
                    db('user_integral')->where(['id' => $user_integral_id])->update($user_integral_data);
                }
            } else {
                // 如果学员表里面没有顾问ID
                // 如果粉丝表里面有，就吧粉丝表的顾问写入学员表
                $counselor_id = $fans->counselor_id;
                if (!$counselor_id) {
                    $counselor_id = $fans->parent_id;
                }
                if ($counselor_id) {
                    $student_id = $org_student['id'];
                    db('students')->where(['id' => $student_id])->update(array('counselor_id' => $counselor_id));
                }
            }

        } else {
            // 写入学员表的时候，就要记录顾问ID
            $counselor_id = $fans->counselor_id;
            if (!$counselor_id) {
                $counselor_id = $fans->parent_id;
            }
            if ($counselor_id) {
                $save_data['counselor_id'] = $counselor_id;
            }
            $save_data['phone_bind_status'] = 1;
            $student = new Students();
            $res = $student->save($save_data);
        }

        if (false === $res) {
            return ['status' => 0, 'msg' => '完善资料失败!'];
        } else {
            //更新students_id
            $fans->students_id = $org_student ? $org_student['id'] : $student->id;
            $r = $fans->save();
            if (false === $r) {
                return ['status' => 0, 'msg' => '完善资料失败.'];
            } else {
                return ['status' => 1, 'msg' => '完善资料成功'];
            }

        }
    }


    /**
     * 微信端: 顾问新增学员
     * @param $sid
     * @param $uid
     * @param $param
     * @return array
     */
    public function addNewStudentByCounselor($sid, $uid, $param)
    {
        $is_counselor = db('user_integral')->where(['sid' => $sid, 'userid' => $uid])->value('counselor_status');
        if(!$is_counselor){
            return ['status' => 0, 'msg' => '无操作权限'];
        }

        $student = db('students')->where(['sid' => $sid, 'phone' => $param['phone']])->find();
        if($student){
            return ['status' => 0, 'msg' => '该学员已存在'];
        }

        $save_data = [
            'sid' => $sid,
            'counselor_id' => $uid,
            'is_counselor' => 0,
            'name' => $param['real_name'],
            'phone' => $param['phone'],
            'website' => $param['website'] ?? '',
            'remark' => $param['remark'] ?? '',
            'company' => $param['company'] ? Util::serializeStr($param['company']) : '',
            'addtime' => time()
        ];
        $res = db('students')->insert($save_data);
        return $res ? ['status' => 1, 'msg' => '新增成功'] : ['status' => 0, 'msg' => '新增失败'];
    }

    /**
     * 获取当天新增客户数量
     * @param int $sid
     * @param int $uid
     */
    public function getIncCustomersCount($sid, $uid)
    {
        $where = [
            'ui.sid' => $sid,
            'ui.parent_id' => $uid,
            'ui.counselor_status' => 0,
            'ui.students_id' => ['>', 0],
        ];

        $inc_count = db()->name('user_integral')
            ->alias('ui')
            ->join('students s', 'ui.students_id = s.id')
            ->where($where)
            ->whereTime('s.addtime', 'today')
            ->count();

        return $inc_count;
    }

    public function getIncCustomersCountNew($sid, $uid)
    {
        $where = [
            's.sid' => $sid,
            'ui.parent_id|ui.counselor_id|s.counselor_id' => $uid,
            's.is_counselor' => 0
        ];
        $inc_count = db('students s')
            ->join('user_integral ui', 'ui.students_id = s.id', 'LEFT')
            ->where($where)
            ->whereTime('s.addtime', 'today')
            ->count();

        return $inc_count;
    }


    /**
     * 获取新增粉丝数量
     * @param int $sid
     * @param int $uid
     */
    public function getIncFansCount(UserIntegral $uiModel, $sid, $uid)
    {
        $where = [
            'sid' => $sid,
            'parent_id' => $uid,
            'counselor_status' => 0,
            'students_id' => 0,
            'userid' => ['>', 0],
            'is_read' => 0
        ];

//         $inc_count = $uiModel->where($where)->whereTime('addtime', 'today')->count();
        $inc_count = $uiModel->where($where)->count();

        return $inc_count;
    }

    /**
     * 获取顾问信息
     * @param UserIntegral $uiModel
     * @param int $sid
     * @param int $uid
     */
    public function getCounselorInfo(UserIntegral $uiModel, $sid, $uid)
    {
        $where = [
            'sid' => $sid,
            'userid' => $uid,
            'counselor_status' => 1
        ];
        return $uiModel::get($where);
    }

    /**
     * 获取客户最近拜访时间
     * @param Visiting $visitingModel
     * @param int $sid
     * @param int $uid
     * @param int $cid
     */
    protected function getVisitingNextTime($sid, $uid, $cid)
    {
        $where = [
            'store_id' => $sid,
            'uid' => $cid,
            'create_uid' => $uid,
            'next_time' => ['gt', time()]
        ];
        $visitingModel = new Visiting();
        $info = $visitingModel->where($where)->order('next_time desc')->find();

        if (!empty($info['next_time'])) {
            return date('m/d', $info['next_time']);
        } else {
            return null;
        }
    }

    protected function getVisitingNextTimeNew($sid, $uid, $cid, $student_id)
    {
        $where = [
            'store_id' => $sid,
            'create_uid' => $uid,
            'next_time' => ['gt', time()]
        ];
        if ($cid) {
            $where['uid'] = $cid;
        } else {
            $where['student_id'] = $student_id;
        }

        $visitingModel = new Visiting();
        $info = $visitingModel->where($where)->order('next_time desc')->find();

        if (!empty($info['next_time'])) {
            return date('m/d', $info['next_time']);
        } else {
            return null;
        }
    }

    /**
     * 获取某粉丝动态数量
     * @param unknown $sid
     * @param unknown $uid
     * @param unknown $pid
     * @return unknown
     */
    protected function getFansDynamicCount($sid, $uid, $pid)
    {
        $where = [
            'sid' => $sid,
            'uid' => $uid,
            'pid' => $pid
        ];

        $trackModel = new Track();

        $count = $trackModel->where($where)->count();

        return $count;
    }

    protected function isWxFriend($sid, $uid, $pid)
    {
        $where = [
            'sid' => $sid,
            'uid' => $uid,
            'natural_id' => $pid
        ];

        $trackModel = new Track();

        $track = $trackModel->where($where)->order('track_id DESC')->find();

        if ($track) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param $sid
     * @param $uid
     * 推广名片
     */
    public function getPromotedCard($sid, $uid)
    {
        $field = 'store_name,owner_name,logo';
        $store_info = db('store')->where(['store_id' => $sid])->field($field)->find();
        $qrcode_url = $this->get_qrcode_url_user($sid, $uid);
        $url = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . $qrcode_url['ticket'];
        $img_path = $this->get_image_url($url);

        $finfo = finfo_open(FILEINFO_MIME_TYPE);

        $mimetype = finfo_file($finfo, $img_path);
        switch ($mimetype) {
            case 'image/jpg':
            case 'image/jpeg':
                $imagecreatefromjpeg = 'imagecreatefromjpeg';
                break;
            case 'image/png':
                $imagecreatefromjpeg = 'imagecreatefrompng';
                break;
            case 'image/gif':
            default:
                $imagecreatefromjpeg = 'imagecreatefromstring';
                break;
        }

        $img = $imagecreatefromjpeg($img_path);

        header("Content-type: image/jpg");
        imagejpeg($img);
        imagedestroy($img);

        unlink($img_path);

        dump($img);
        die();
    }

    public function get_qrcode_url_user($sid, $uid)
    {
        $integral = db('user_integral')->where(['sid' => $sid, 'userid' => $uid])->field('ticket,ticket_url')->find();
        if (!$integral) {
            return ['status' => -1, 'sid' => $sid, 'userid' => $uid];
        }
        if (!empty($integral['ticket']) && !empty($integral['ticket_url'])) {
            return ['status' => 1, 'ticket' => $integral['ticket'], 'url' => $integral['ticket_url']];
        }
    }

    public function get_image_url($url, $data = null)
    {
        $time = microtime(true) * 10000; //time();
        $timeout = 5;
        $headers['CLIENT-IP'] = '202.103.229.40';
        $headers['X-FORWARDED-FOR'] = '202.103.229.40';
        $headerArr = array();
        foreach ($headers as $n => $v) {
            $headerArr[] = $n . ':' . $v;
        }

        ob_start();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        if (!empty($data)) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $return = curl_exec($ch);
        curl_close($ch);

        ob_clean();
        $image_url = "../public/uploads/Icon/$time.jpg";
        $fopen = fopen($image_url, "w");
        fwrite($fopen, $return);
        fclose($fopen);
        return $image_url;
    }

    /**
     * 添加或者修改用户资料
     * @param $data 数据资料
     * @param int $user_id 这个是0就是新增
     */
    public function editUserByID($data, $user_id = 0)
    {
        $user = new User();
        if ($user_id) {
            $data['create_time'] = time();
            $data['status'] = 1;
            $user->save($data, ['user_id' => $user_id]);

        } else {
            $user->save($data);
        }
    }

    /**
     * 使用user_id获得用户资料
     * @param int $user_id
     */
    public function getUserByID($user_id = 0)
    {
        $user = User::get($user_id);
        return $user;
    }

    /**
     * 使用user_id获得用户资料
     * @param int $user_id
     */
    public function getUserByOpenId($open_id = 0)
    {
        $user = new User();
        $user = $user->where('user_openid', $open_id)
            ->find();
        return $user;
    }

    public function editUserIntegralByOpenId($data, $sid, $open_id)
    {
        // 用open_id去获得userid
        $user = new User();
        $user_id = $user->getUserIdByOpenId($open_id);
        if (!$user_id) {
            return false;
        }

        return $this->editUserIntegralByUserId($data, $sid, $user_id);
    }

    public function editUserIntegralByUserId($data, $sid, $userid)
    {
        $where = [
            'sid' => $sid,
            'userid' => $userid
        ];

        $user_integral = new UserIntegral();
        return $user_integral->save($data, $where);
    }

    /**
     * 用open_id修改用户
     * 这个就是微信授权后调用
     * @param $data
     * @param $open_id
     */
    public function editUserByOpenId($data, $sid, $open_id)
    {
        $user = new User();
        $user_id = $user->getUserIdByOpenId($open_id);

        if (isset($data['user_nickname'])) {
            $user_nickname = $data['user_nickname'];
            $data['user_nickname'] = Util::json_name($user_nickname);
        }

        if ($user_id) {
            $data['create_time'] = time();
            $data['status'] = 1;
            $user->save($data, ['user_id' => $user_id]);

            $user = User::get($user_id);
        } else {
            $user->save($data);
            $user_id = $user->user_id;

            $data_integral = array();
            $data_integral['sid'] = $sid;
            $data_integral['userid'] = $user_id;
            $data_integral['touser'] = $open_id;

            $data_integral['addtime'] = time();
            $data_integral['ticket'] = '';
            $data_integral['ticket_url'] = '';
            $data_integral['ticket_qrcode_url'] = '';

            $data_integral['parent_id'] = 0;
            $data_integral['natural_id'] = 0;


            //$data_integral['is_subscribe'] = 1;
            //$data_integral['subscribe_time'] = time();


            $baseHelper = new \app\common\helper\BaseHelper();

            $user_integral = new UserIntegral();
            $user_integral->save($data_integral);

            $place = $baseHelper->getPlace();
            $url2 = $baseHelper->getUrl('_back_url');
            if ($url2) {
                $url = $url2;
                $url = urldecode($url);
                $url = urldecode($url);

            } else {
                $url = $baseHelper->getUrl();
            }


            db('user_integral_browse')->insert(array(
                'integral_id' => $user_integral->id,
                'url' => $url,
                'place' => $place,
                'code' => 1,
                'addtime' => time()));

        }
        return $user;
    }


    /**
     * @param $sid
     * @param $search
     * @param $p
     * @param $pageSize
     * @return false|\PDOStatement|string|\think\Collection
     * 获取会员列表 ，后台使用
     */
    public function getMemberList($sid, $search, $no_parent, $p, $pageSize)
    {
        //获取会员基本列表信息
        $where = [
            'ui.sid' => $sid,
            'u.status' => 1
        ];
        if (!empty($search)) {
//            $where['u.user_mobile|u.user_nickname'] = $search;
            //更改为模糊搜索
            $where['u.user_mobile|u.user_nickname'] = ['like', "%$search%"];
        }

        //查询无顾问会员
        if ($no_parent == 1) {
            $where['ui.parent_id'] = 0;
            $where['ui.counselor_id'] = 0;
            $where['ui.counselor_status'] = 0;
        }

        $field = 'u.user_id as uid,u.user_nickname,u.user_headimgurl,ui.sid,ui.addtime,ui.parent_id,ui.counselor_status,ui.students_id,s.formal_status';
        $list_count = db()->name('user_integral')
            ->alias('ui')
            ->join('user u', 'u.user_id = ui.userid')
            ->join('students s', 's.id = ui.students_id', 'left')
            ->where($where)
            ->order('ui.addtime desc')
            ->count();
        $member_list = $this->getMemberBaseList($sid, $where, $field, $p, $pageSize);

        if ($member_list) {
            $trackService = new TrackService();
            foreach ($member_list as $k => $v) {
                //判断会员当前状态
                $member_list[$k]['member_type'] = $this->getMemberType($v);

                //获取某个用户阅读文章次数，即：轨迹数量
                $member_list[$k]['reading_count'] = $trackService->getTrackCountByOne($sid, $v['uid']);

                if ($v['counselor_status'] == 0 && $v['parent_id'] > 0) {
                    //获取上级（顾问）昵称
                    $member_list[$k]['counselor_name'] = $this->getUserNicknameByUID($v['parent_id']);
                } else {
                    $member_list[$k]['counselor_name'] = '';
                }

            }
        }
        return ['content' => $member_list, 'page' => ['count' => $list_count]];
    }

    /**
     * @param $sid
     * @param $search
     * @param $p
     * @return false|\PDOStatement|string|\think\Collection
     * 获取会员基本列表
     */
    public function getMemberBaseList($sid, $where = [], $field, $p, $pageSize)
    {
        $member_list = db()->name('user_integral')
            ->alias('ui')
            ->field($field)
            ->join('user u', 'u.user_id = ui.userid')
            ->join('students s', 's.id = ui.students_id', 'left')
            ->where($where)
            ->order('ui.addtime desc')
            ->limit(($p - 1) * $pageSize, $pageSize)
            ->select();
        if ($member_list) {
            foreach ($member_list as $k => $v) {
                if ($v['addtime']) {
                    $member_list[$k]['addtime'] = date('Y-m-d H:i:s', $v['addtime']);
                }
            }
        }

        return $member_list;
    }


    /**
     * @param $user_info
     * @return int
     * 获取会员当前状态  1：粉丝（潜在客户）  2：意向客户  3：正式客户  4：顾问
     */
    public function getMemberType($user_info)
    {
        if ($user_info) {
//            $member_type = $user_info['counselor_status'] == 1 ? 3 : ($user_info['students_id'] > 0 ? 2 : 1);
            $member_type = $user_info['counselor_status'] == 1 ? 4 : ($user_info['students_id'] > 0 ? ($user_info['formal_status'] == 1 ? 3 : 2) : 1);
            return $member_type;
        } else {
            return false;
        }
    }

    public function getMemberType2($user_info)
    {
        if ($user_info) {
            $member_type = $user_info['counselor_status'] == 1 ? 3 : ($user_info['students_id'] > 0 ? 2 : 1);
            return $member_type;
        } else {
            return false;
        }
    }


    /**
     * @param $uid
     * @return mixed
     * 获取用户昵称
     */
    public function getUserNicknameByUID($uid)
    {
        return User::where(['user_id' => $uid])->value('user_nickname');
    }


    /**
     * @param $sid
     * @param $uid
     * @return array|false|\PDOStatement|string|Model
     * 获取用户基本信息
     */
    public function getUserBaseInfo($sid, $uid)
    {
        $field = 'u.user_id as uid,u.user_openid,u.user_nickname,u.user_headimgurl,ui.sid,ui.addtime,ui.parent_id,ui.counselor_status,ui.students_id,ui.natural_id,ui.counselor_id';
        $where = [
            'ui.sid' => $sid,
            'ui.userid' => $uid
        ];
        $user_info = db()->name('user_integral')
            ->alias('ui')
            ->field($field)
            ->join('user u', 'u.user_id = ui.userid')
            ->where($where)
            ->find();
        $user_info['addtime'] = date('Y-m-d H:i:s', $user_info['addtime']);
        //
        // 因为一个用户，可能访问几个客户，遭成session混乱
        //
        //
        if ($user_info && isset($user_info['counselor_status'])) {
            $user_info['member_type'] = $this->getMemberType2($user_info);
            return $user_info;
        } else {
            return false;
        }
    }

    /**
     * @param $sid
     * @param $uid
     * @param $counselor_status
     * @param $counselor_rank_id
     * @return array
     * 编辑自身顾问状态
     */
    public function editCounselorStatus($sid, $uid, $counselor_status, $counselor_rank_id)
    {
        $false_result = ['status' => 0, 'msg' => '设置失败'];
        $suc_result = ['status' => 1, 'msg' => '设置成功'];
        //获取用户当前信息
        $cur_counselor_status = db('user_integral')->where(['sid' => $sid, 'userid' => $uid])->value('counselor_status');
        if ($counselor_status == 1) {
            //设为顾问
            if ($cur_counselor_status == 0) {
//                $result = $this->becomeCounselor($sid, $uid, $counselor_rank_id) === false ? $false_result : $suc_result;
                $result = $this->becomeCounselor($sid, $uid, $counselor_rank_id);
                if ($result === false) {
                    return $false_result;
                } else {
                    //获取当前用户基本信息返回给前端
                    $suc_result['data']['content'] = $this->getUserBaseInfo($sid, $uid);
                    return $suc_result;
                }
            } else {
                return $false_result;
            }
        } elseif ($counselor_status == 0) {
            //取消顾问
            if ($cur_counselor_status == 1) {
                return $this->cancelCounselor($sid, $uid);
            } else {
                return $false_result;
            }
        } else {
            return $false_result;
        }
    }

    /**
     * @param $sid
     * @param $uids
     * @param $counselor_status
     * @return array
     * 批量设置自身顾问状态
     */
    public function editCounselorStatusBatch($sid, $uids, $counselor_status, $counselor_rank_id)
    {
        $false_result = ['status' => 0, 'msg' => '设置失败'];
        $suc_result = ['status' => 1, 'msg' => '设置成功'];
        if (is_array($uids) && count($uids) > 0) {
            //获取uids的所有用户信息
            $user_infos = db('user_integral')->field('userid,counselor_status')->where(['sid' => $sid, 'userid' => ['in', $uids]])->select();

            if ($user_infos) {
                if ($counselor_status == 1) {
                    //设为顾问
                    foreach ($user_infos as $k => $v) {
                        //若存在用户是顾问  则设置失败
                        if ($v['counselor_status'] != 0) {
                            return ['status' => 0, 'msg' => '批量设置失败'];
                        }
                    }
                    $result = db('user_integral')
                        ->where(['sid' => $sid, 'userid' => ['in', $uids]])
                        ->update(['counselor_status' => 1, 'counselor_edittime' => time(), 'counselor_rank_id' => $counselor_rank_id, 'parent_id' => 0]);
                } else {
                    //取消顾问
                    foreach ($user_infos as $k => $v) {
                        //若存在用户不是顾问  则设置失败
                        if ($v['counselor_status'] != 1) {
                            return ['status' => 0, 'msg' => '批量设置失败'];
                        }
                    }
                    $result = db('user_integral')->where(['sid' => $sid, 'userid' => ['in', $uids]])->update(['counselor_status' => 0, 'counselor_edittime' => '', 'counselor_rank_id' => 0]);
                }
                $r = $result === false ? $false_result : $suc_result;

                //将设置成功的用户信息返回给前端
                if ($result !== false) {
                    $where = [
                        'ui.sid' => $sid,
                        'ui.userid' => ['in', $uids]
                    ];
                    $field = 'u.user_id as uid,u.user_nickname,u.user_headimgurl,ui.sid,ui.addtime,ui.parent_id,ui.counselor_status,ui.students_id,s.formal_status';
                    $member_list = db()->name('user_integral')
                        ->alias('ui')
                        ->field($field)
                        ->join('user u', 'u.user_id = ui.userid')
                        ->join('students s', 's.id=ui.students_id', 'LEFT')
                        ->where($where)
                        ->select();
                    if ($member_list) {
                        foreach ($member_list as $key => $val) {
                            $member_list[$key]['addtime'] = date('Y-m-d H:i:s', $val['addtime']);
                            $member_list[$key]['member_type'] = $this->getMemberType($val);
                        }
                    }
                    $r['data']['content'] = $member_list;
                }

                return $r;
            } else {
                return ['status' => 0, 'msg' => '不存在相关用户'];
            }

        } else {
            return ['status' => 0, 'msg' => '批量设置失败'];
        }

    }

    /**
     * @param $sid
     * @param $uid
     * @param $counselor_rank_id
     * @return int
     * 自身设为顾问
     */
    public function becomeCounselor($sid, $uid, $counselor_rank_id)
    {
//        return db('user_integral')->where(['sid' => $sid, 'userid' => $uid])->setField('counselor_status',1);

        $user_info = $this->getUserBaseInfo($sid, $uid);
        $user_openid = $user_info['user_openid'];
        $res = WeixinHelper::set_user_group($sid, $user_openid, 100);
        if ($res) {
            $students = db('students')->where(['sid' => $sid, 'uid' => $uid])->find();
            if ($students && $students['is_counselor'] == 0) {
                //此情况是先为学员，后成为顾问的情况
                //更新学员表顾问状态字段
                db('students')->where(['sid' => $sid, 'uid' => $uid])->setField('is_counselor', 1);
            }
            return db('user_integral')
                ->where(['sid' => $sid, 'userid' => $uid])
                ->update(['counselor_status' => 1, 'counselor_edittime' => time(), 'counselor_rank_id' => $counselor_rank_id, 'parent_id' => 0]);
        } else {
            return false;
        }
    }

    /**
     * @param $sid
     * @param $uid
     * @return bool|int
     * 取消顾问资格
     */
    public function cancelCounselor($sid, $uid)
    {
        //查询当前用户是否存在粉丝或客户
        $children = db('user_integral')
                    ->where(['sid' => $sid, 'parent_id' => $uid, 'userid' => ['<>', $uid]])
                    ->count();
        if ($children > 0) {
            return ['status' => 0, 'msg' => '当前顾问存在粉丝或客户，请转移后再取消'];
        }

        $user_info = $this->getUserBaseInfo($sid, $uid);
        $user_openid = $user_info['user_openid'];
        WeixinHelper::set_user_group($sid, $user_openid, 0);

        $students = db('students')->where(['sid' => $sid, 'uid' => $uid])->find();
        if ($students && $students['is_counselor'] == 1) {
            //此情况是先为学员，后成为顾问的情况
            //更新学员表顾问状态字段
            db('students')->where(['sid' => $sid, 'uid' => $uid])->setField('is_counselor', 0);
        }

//        $result = db('user_integral')->where(['sid' => $sid, 'userid' => $uid])->setField('counselor_status',0);
        $result = db('user_integral')->where(['sid' => $sid, 'userid' => $uid])->update(['counselor_status' => 0, 'counselor_edittime' => '', 'counselor_rank_id' => 0]);
        $r = $result === false ? ['status' => 0, 'msg' => '设置失败'] : ['status' => 1, 'msg' => '设置成功'];
        if ($result !== false) {
            //获取当前用户基本信息返回给前端
            $r['data'] = $this->getUserBaseInfo($sid, $uid);
        }

        return $r;
    }


    /**
     * @param $sid
     * @param $search
     * @param $p
     * @return false|\PDOStatement|string|\think\Collection
     * 获取顾问列表
     */
    public function getCounselorList($sid, $search, $p, $pageSize)
    {
        //获取会员基本列表信息
        $where = [
            'ui.sid' => $sid,
            'u.status' => 1,
            'ui.counselor_status' => 1
        ];
        if (!empty($search)) {
            $where['u.user_mobile|u.user_nickname|s.name'] = $search;
        }
        $field = 'u.user_id as uid,u.user_openid,u.user_nickname,u.user_headimgurl,ui.sid,ui.addtime,ui.parent_id,ui.counselor_status,ui.students_id,ui.is_ac_admin';
        $counselor_list = $this->getMemberBaseList($sid, $where, $field, $p, $pageSize);
        $list_count = db()->name('user_integral')
            ->alias('ui')
            ->join('user u', 'u.user_id = ui.userid')
            ->join('students s', 's.id = ui.students_id', 'left')
            ->where($where)
            ->count();
        return ['content' => $counselor_list, 'page' => ['count' => $list_count]];
    }

    /**
     * @param $sid
     * @param $uid
     * @param $counselor_id
     * @param $status 1为设置上级顾问，0为取消上级顾问
     * @return array
     * 编辑（设置或取消）上级顾问
     */
    public function editParentCounselor($sid, $uid, $counselor_id, $status)
    {
        //$user_status = db('user_integral')->where(['sid' => $sid, 'userid' => $uid])->value('counselor_status');
        $user_info = db('user_integral')->where(['sid' => $sid, 'userid' => $uid])->field('counselor_status,parent_id')->find();
        if ($user_info['counselor_status'] == 1) {
            return ['status' => 0, 'msg' => '当前用户无法设置上级顾问'];
        }

        $counselor_status = db('user_integral')->where(['sid' => $sid, 'userid' => $counselor_id])->value('counselor_status');

        if ($counselor_status != 1) {
            return ['status' => 0, 'msg' => '不存在上级顾问'];
        }

        $counselor_id = $status == 1 ? $counselor_id : 0;
        $result = db('user_integral')->where(['sid' => $sid, 'userid' => $uid])->update(['parent_id' => $counselor_id, 'counselor_id' => $counselor_id]);
        db('students')->where(['sid' => $sid, 'uid' => $uid])->setField('counselor_id', $counselor_id);

        if ($result === false) {

            return ['status' => 0, 'msg' => '设置失败'];
        } else {
            if ($status == 1) {
                //推送消息
                $tplServer = new WxTplMsgService();
                $tplServer->send($sid, $uid, 'user');
            }

            //添加记录表
            $add_data = [
                'sid' => $sid,
                'uid' => $uid,
                'pre_counselor_id' => $user_info['parent_id'],
                'cur_counselor_id' => $counselor_id,
                'addtime' => time()
            ];
            db('change_counselor_log')->insert($add_data);
            return ['status' => 1, 'msg' => '设置成功'];
        }
    }

    /**
     * @param $sid
     * @param $uids
     * @param $counselor_id
     * @param $status 1为设置上级顾问，0为取消上级顾问
     * @return array
     * 批量编辑（设置或取消）上级顾问
     */
    public function editParentCounselorBatch($sid, $uids, $counselor_id, $status)
    {
        if (!is_array($uids) || count($uids) < 1) {
            return ['status' => 0, 'msg' => '参数错误'];
        }

        // 取消顾问
        if($status == 0){
            $r = db('user_integral')->where(['sid' => $sid, 'userid' => ['in', $uids]])->update(['parent_id' => 0, 'counselor_id' => 0]);
            $res = db('students')->where(['sid' => $sid, 'uid' => ['in', $uids]])->setField('counselor_id', 0);
            if($r === false || $res === false){
                return ['status' => 0, 'msg' => '批量取消顾问失败'];
            } else {
                return ['status' => 1, 'msg' => '批量取消顾问成功'];
            }
        }

        //设置上级顾问时，查询上级是否为顾问状态
        $counselor_status = db('user_integral')->where(['sid' => $sid, 'userid' => $counselor_id])->value('counselor_status');

        if ($counselor_status != 1) {
            return ['status' => 0, 'msg' => '不存在上级顾问'];
        }


        foreach ($uids as $k => $uid) {
            $user_info = db('user_integral')->where(['sid' => $sid, 'userid' => $uid])->field('counselor_status,parent_id')->find();
            if ($user_info['counselor_status'] == 1) {
                return ['status' => 0, 'msg' => '当前用户无法设置上级顾问'];
            }
            $add_data[] = [
                'sid' => $sid,
                'uid' => $uid,
                'pre_counselor_id' => $user_info['parent_id'],
                'cur_counselor_id' => $counselor_id,
                'addtime' => time()
            ];
        }


        $restult = db('user_integral')->where(['sid' => $sid, 'userid' => ['in', $uids]])->update(['parent_id' => $counselor_id, 'counselor_id' => $counselor_id]);
        $re = db('students')->where(['sid' => $sid, 'uid' => ['in', $uids]])->setField('counselor_id', $counselor_id);
        if ($restult === false || $re === false) {
            return ['status' => 0, 'msg' => '设置失败'];
        } else {
            if ($status == 1) {
                foreach ($uids as $k => $uid) {
                    //推送消息
                    $tplServer = new WxTplMsgService();
                    $tplServer->send($sid, $uid, 'user');
                }
            }

            db('change_counselor_log')->insertAll($add_data);
            return ['status' => 1, 'msg' => '设置成功'];
        }
    }

    /**
     * @param $sid
     * @return false|\PDOStatement|string|\think\Collection
     * 获取顾问等级列表
     */
    public function getCounselorRankList($sid)
    {
        $list = db('counselor_rank')->field('counselor_rank_id,name')->where(['sid' => $sid, 'status' => 1])->order('counselor_rank_id DESC')->select();
        $list_count = db('counselor_rank')->where(['sid' => $sid, 'status' => 1])->count();
        return ['content' => $list, 'page' => ['count' => $list_count]];
    }


    public function getDefaultPid($sid, $uid, $pid = 0)
    {
        $reset_parents = db('store')->where(array('store_id' => $sid))->value('reset_parents');
        $user_info = db('user_integral')->where(array('sid' => $sid, 'userid' => $uid))->field('parent_id,counselor_status')->find();
        if ($reset_parents == 1 && $user_info['parent_id'] == 0 && $user_info['counselor_status'] == 0) {
            if ($pid == 0) {

                $recommend_dis = db('store')->where(array('store_id' => $sid))->value('recommend_dis');
                if ($recommend_dis == 4) {
                    $pid = db('user_integral')->where(array('is_administrator' => 1, 'sid' => $sid))->value('userid');
                }
            }
            if ($pid) {
                return $pid;
            }
        }
        return 0;
    }


    /**
     * 同步微信粉丝
     * @param $sid
     * @return array
     */
    public function syncWxFans($sid)
    {
        $users = WeixinHelper::getUserList($sid);
        $users = json_decode($users, 1);
        $open_ids = $users['data']['openid'];
        if (!$open_ids) {
            return ['status' => 0, 'msg' => '微信粉丝为空'];
        }
        $res = db('user_integral')->where(['sid' => $sid, 'touser' => ['in', $open_ids]])->setField('is_subscribe', 1);

        return $res === false ? ['status' => 0, 'msg' => '同步粉丝失败'] : ['status' => 1, 'msg' => '同步粉丝成功'];
    }

    /**
     * 获得一个人的轨迹
     * 直接关系，包含来源
     * 关系链
     * @param $sid
     */
    public function getUserInfoTrail($sid, $uid)
    {
        $userinfo = db('user_integral')->where(['sid' => $sid, 'userid' => $uid])->find();
        $integral_id = 0;
        if ($userinfo) {
            $integral_id = $userinfo['id'];
            $user_integral_browse = db('user_integral_browse')->where(['integral_id' => $integral_id])->find();
            $res1 = false;
            $res2 = false;
            if ($user_integral_browse) {
                /*
                $res1 = $this->getUserInfoTrailText($user_integral_browse,$userinfo);
                if(!$res1)
                {
                    $res1 = false;
                }
                $res2 = $this->getUserInfoTrailAllText($sid,$userinfo);
                if(!$res2)
                {
                    $res2 = false;
                }
                */

                $res1 = $this->getUserInfoTrailText($user_integral_browse, $userinfo);
                if (empty($res1)) {
                    $res1 = false;
                }
                $res2 = $this->getUserInfoTrailAllText($sid, $userinfo);
                if (empty($res2)) {
                    $res2 = false;
                }

            }

            return ['status' => 1, 'msg' => '获取成功', 'data' => ['origin' => $res1, 'trail' => $res2]];
            //return $this->apiResult(['origin'=>$res1,'trail'=>$res2],200,'获取成功');
        } else {
            return ['status' => 0, 'msg' => '获取失败，请重试！'];
            //return $this->apiResult('',404,'获取失败，请重试！');
        }

    }

    public function getUserInfoTrailText($user_integral_browse, $userinfo)
    {
        $res = '';
        $user_browse_id = 0;
        $addtime = date("Y-m-d H:i:s", $user_integral_browse['addtime']);

        if (-1 == $user_integral_browse['place']) {
            if ($userinfo['ticket']) {
                $res = '扫描您的顾问名片';
            } else {
                $res = '主动关注公众号';
            }
            return ['natural_id' => $user_browse_id, 'addtime' => $addtime, 'msg' => $res];
            //return [$user_browse_id,$addtime,$res];
        }
        if (1 == $user_integral_browse['place']) {

            $res = '发送给好友';

            $url = $user_integral_browse['url'];
            $_back_url = '';
            if ($url) {
                $urlArray = parse_url($url);
                $queryArr = explode('&', $urlArray['query']);
                foreach ($queryArr as $k => $para) {
                    $para = explode('=', $para);
                    if ('_back_url' == $para[0]) {
                        $_back_url = $para[1];
                    }
                }
            }
            if ($_back_url) {
                $_back_url = urldecode($_back_url);
                $_back_url = urldecode($_back_url);
                $_back_url = urldecode($_back_url);
            }
            $urlArray = parse_url($_back_url);

            if (isset($urlArray['path']) && '/m/html/magazine.html' == $urlArray['path']) {
                if (isset($urlArray['query'])) {
                    $queryArr = explode('&', $urlArray['query']);

                    $natural_id = '';
                    $news_id = '';
                    $title = '';
                    $counselor_id = '';
                    foreach ($queryArr as $k => $para) {
                        $para = explode('=', $para);
                        if ('id' == $para[0]) {
                            $news_id = $para[1];
                        }
                        if ('natural_id' == $para[0]) {
                            $natural_id = $para[1];
                        }
                        if ('counselor_id' == $para[0]) {
                            $counselor_id = $para[1];
                        }
                    }

                    $user_browse_id = $natural_id * 1;
                    if ($news_id && $natural_id) {
                        $topic_detail = db("magazine")->where(array('mid' => $news_id))->find();
                        $title = $topic_detail['title'];

                        if ($natural_id == $counselor_id) {
                            $res = '阅读了您发送给好友的文章:' . $title;
                        } else {
                            $user_detail = db("user")->where(array('user_id' => $natural_id))->find();
                            $user_nickname = $user_detail['user_nickname'];

                            $res = '阅读了(' . $user_nickname . ')转发给好友的文章:' . $title;
                        }
                    }
                }
            }
        }
        if (2 == $user_integral_browse['place']) {

            $res = '朋友圈分享';

            $url = $user_integral_browse['url'];
            $_back_url = '';
            if ($url) {
                $urlArray = parse_url($url);
                $queryArr = explode('&', $urlArray['query']);
                foreach ($queryArr as $k => $para) {
                    $para = explode('=', $para);
                    if ('_back_url' == $para[0]) {
                        $_back_url = $para[1];
                    }
                }
            }
            if ($_back_url) {
                $_back_url = urldecode($_back_url);
                $_back_url = urldecode($_back_url);
                $_back_url = urldecode($_back_url);
            }
            $urlArray = parse_url($_back_url);

            if (isset($urlArray['path']) && '/m/html/magazine.html' == $urlArray['path']) {
                if (isset($urlArray['query'])) {
                    $queryArr = explode('&', $urlArray['query']);

                    $natural_id = '';
                    $news_id = '';
                    $title = '';
                    $counselor_id = '';
                    foreach ($queryArr as $k => $para) {
                        $para = explode('=', $para);
                        if ('id' == $para[0]) {
                            $news_id = $para[1];
                        }
                        if ('natural_id' == $para[0]) {
                            $natural_id = $para[1];
                        }
                        if ('counselor_id' == $para[0]) {
                            $counselor_id = $para[1];
                        }
                    }

                    $user_browse_id = $natural_id * 1;
                    if ($news_id && $natural_id) {
                        $topic_detail = db("magazine")->where(array('mid' => $news_id))->find();
                        $title = $topic_detail['title'];

                        if ($natural_id == $counselor_id) {
                            $res = '阅读了您分享在朋友圈的文章:' . $title;
                        } else {
                            $user_detail = db("user")->where(array('user_id' => $natural_id))->find();
                            $user_nickname = $user_detail['user_nickname'];

                            $res = '阅读了(' . $user_nickname . ')转发在朋友圈的文章:' . $title;
                        }
                    }
                }
            }
        }
        return ['natural_id' => $user_browse_id, 'addtime' => $addtime, 'msg' => $res];
    }

    public function getUserInfoTrailAllText($sid, $userinfo)
    {
        $res = false;
        $natural_id = $userinfo['natural_id'];
        if ($natural_id && $userinfo['userid'] != $natural_id) {
            $userinfo_temp = db('user_integral')->where(['sid' => $sid, 'userid' => $natural_id])->find();
            if ($userinfo_temp) {
                $userinfo_d = db('user')->where(['user_id' => $userinfo_temp['userid']])->find();

                $res[] = [
                    'userid' => $userinfo_temp['userid'],
                    'user_nickname' => $userinfo_d['user_nickname'],
                    'user_name' => $userinfo_d['user_name'],
                    'user_headimgur' => $userinfo_d['user_headimgurl'],
                    'user_mobile' => $userinfo_d['user_mobile'],
                    'natural_id' => $userinfo_temp['natural_id']
                ];


                if ($userinfo_temp['natural_id']) {
                    $res2 = $this->getUserInfoTrailAllText($sid, $userinfo_temp);
                    if (is_array($res) && is_array($res2)) {
                        $res = array_merge($res, $res2);
                    }
                }
            }
        }
        return $res;
    }

}






















